package com.zp.datax.core.util;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;

/**
 * 时间处理帮助类
 *
 * @author bruce
 * @date 2019-07-15
 */
public final class TimeUtil {

    /**
     * 将毫秒转换成 yyyy-MM-dd'T'HH24:mi:ss
     *
     * @param timeMillis
     * @return
     */
    public static String parserT(long timeMillis) {
        Calendar calendar = getCalendar(timeMillis);
        return LocalDateTime.ofInstant(calendar.toInstant(), ZoneId.systemDefault())
                .format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"));
    }

    /**
     * 将毫秒转换成 yyyy-MM-dd HH24:mi:ss
     *
     * @param timeMillis
     * @return
     */
    public static String parser(long timeMillis) {
        return parserT(timeMillis)
                .replace("T", " ");
    }

    /**
     * 将毫秒转换成Date
     *
     * @param timeMillis
     * @return
     */
    public static Date convert(long timeMillis) {
        return getCalendar(timeMillis).getTime();
    }

    /**
     * 将毫秒转换成Calendar
     *
     * @param timeMillis
     * @return
     */
    private static Calendar getCalendar(long timeMillis) {
        Calendar instance = Calendar.getInstance();
        instance.setTimeInMillis(timeMillis);
        return instance;
    }

    /**
     * 将字符患上日期转换成毫秒
     *
     * @param datetime
     * @return
     */
    public static long convert(String datetime) {
        LocalDateTime parse = LocalDateTime.parse(datetime, DateTimeFormatter.ISO_DATE_TIME);
        return parse.toInstant(ZoneOffset.of("+8")).toEpochMilli();
    }

    public static LocalDateTime convertLocalDataTime(long timeMillis) {
        return new Date(timeMillis).toInstant().atOffset(ZoneOffset.of("+8")).toLocalDateTime();
    }

    public static Date convertDate(LocalDateTime localDateTime) {
        ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }
}
